#!/usr/bin/python3
# -*- coding:utf-8 -*-
# @Time   :2021/12/8
# @Author :CJX
# @File   :DHT11.py
import RPi.GPIO as GPIO
import dht11
import time
import pymysql
from dox_enquiry import dox_command


def DHT11(temperature, humidity):
    humidity_t = 0
    temperature_t1 = 0
    temperature_t2 = 0
    while 1:
        global err_inquiry_8, err_inquiry_12
        con = pymysql.connect(
            host='localhost',
            port=3306,
            user='root',
            password='!qAz2WsX3edc',
            db='ph',
            charset='utf8'
        )
        cur = con.cursor()
        address = "DHT11"
        GPIO.setwarnings(False)
        GPIO.setmode(GPIO.BCM)
        GPIO.cleanup()
        instance = dht11.DHT11(pin=18)  # DHT11连接的引脚
        a = 0
        while a <= 10:
            result = instance.read()
            if result.is_valid():
                temperature = int(float('%-3.1f' % result.temperature))
                humidity = int(float('%-3.1f' % result.humidity))

                if humidity > 85:
                    dox_command([8], err_inquiry_8)
                    humidity_t = 1
                    sql_insert_err("环境温度高")
                elif humidity < 83 and humidity_t == 1:
                    humidity_t = 0
                    dox_command([0], err_inquiry_8)
                    sql_insert_err("环境温度正常")

                if temperature > 40:
                    dox_command([8], err_inquiry_8)
                    temperature_t1 = 1
                    sql_insert_err("环境温度高")
                elif temperature < 35 and temperature_t1 == 1:
                    temperature_t1 = 0
                    dox_command([0], err_inquiry_8)
                    sql_insert_err("环境温度正常")

                if temperature < 5:
                    temperature_t2 = 1
                    dox_command([12], err_inquiry_12)
                    sql_insert_err("环境温度低")
                elif temperature > 10 and temperature_t2 == 1:
                    temperature_t2 = 0
                    dox_command([0], err_inquiry_12)
                    sql_insert_err("环境温度正常")
                print("温度是： ", temperature, "湿度是： ", humidity)
                time1 = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time()))
                cur.executemany(
                    "INSERT DHT11(address,time,temperature,humidity) VALUE(%s,%s,%s,%s)",
                    [(address, time1, temperature, humidity)])
                con.commit()
                cur.close()
                a = 11
                time.sleep(5)
                return
            else:
                a = 0


DHT11(0, 0)
